<template>
    <div>
        <InnerBreadcrumb v-model="currentPage" :path="breadPath"></InnerBreadcrumb>
        <div v-show="currentPage === 'home'" class="homePage">
            <ConditionCard @search="fetchFlowTypeList" @reset="reset('filterForm')">
                <el-form :model="filterApproval" ref="filterForm" label-width="150px">
                    <el-row>
                        <el-col :span="8" v-for="item in filterApprovalOpt" :key="item.label">
                            <el-form-item :label="setColon(item.label)" :prop="item.name">
                                <el-select v-model="filterApproval[item.name]" style="width: 100%" clearable>
                                    <el-option
                                        v-for="it in selectOptType(item.optType)"
                                        :key="it.value"
                                        :label="it.label"
                                        :value="it.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </ConditionCard>
            <div class="homePage-cnt el-card" style="padding: 24px;">
                <p>{{label.flowTypeList}}</p>
                <div class="searchArea">
                    <el-input
                        clearable
                        style="width:240px"
                        :placeholder="label.typeName"
                        v-model="queryFlowTypeParams.name"
                        suffix-icon="el-icon-search"
                        @keyup.enter.native="fetchFlowTypeList"
                    ></el-input>
                    <el-button class="float-right" @click="addFlowType" type="primary">{{label.add}}</el-button>
                </div>
                <edu-table
                    :data="flowTypeTableOpt.data"
                    :total="flowTypeTableOpt.pageOpt.total"
                    :selection=false
                    @page-change="flowTypePageChange"
                    order
                    tooltip-effect="light"
                >
                    <template v-for="item in flowTypeTableOpt.column">
                        <el-table-column                    
                            show-overflow-tooltip 
                            :key="item.label"
                            :label="item.name"
                            :width = "item.width"
                            :align="item.align || 'left'">
                            <template slot-scope="scope">
                                <div v-if="item.operations">
                                    <template v-for="operate in item.operations">
                                        <el-button 
                                            v-if="!operate.dynamicShow || scope.row.specialApproval"
                                            type="text"
                                            size="mini"
                                            :key="operate.label"
                                            @click="operate.click(scope.row)"
                                        >
                                        {{ operate.label }}
                                    </el-button>
                                    </template>
                                </div>
                                <template v-else-if="item.switch && item.tag">
                                    <el-tag :type="item.value === 1 ? 'success' : ''">
                                        {{yesMap[scope.row[item.value]]}}
                                    </el-tag>
                                </template>
                                <template v-else-if="item.switch">{{needMap[scope.row[item.value]]}}</template>
                                <template v-else>{{scope.row[item.value]}}</template>
                            </template>
                        </el-table-column>
                    </template>
                </edu-table>
            </div>
        </div>
        <div v-show="currentPage === 'set'" class="setPage el-card" style="padding: 24px;">
            <div class="searchArea">
                <el-input
                    clearable
                    style="width:240px"
                    :placeholder="label.approver"
                    v-model="queryCertainTypeParams.approver"
                    suffix-icon="el-icon-search"
                    @keyup.enter.native="fetchCertainTypeList"
                ></el-input>
                <el-button class="float-right" @click="addCeratainType" type="primary">{{label.add}}</el-button>
                <el-button class="float-right" @click="goBack">{{label.goBack}}</el-button>
            </div>
            <edu-table
                :data="certainTypeTableOpt.data"
                :total="certainTypeTableOpt.pageOpt.total"
                :selection=false
                @page-change="certainTypePageChange"
                order
                tooltip-effect="light"
            >
                <template v-for="item in certainTypeTableOpt.column">
                    <el-table-column                    
                        show-overflow-tooltip 
                        :key="item.label"
                        :label="item.name"
                        :width = "item.width"
                        :align="item.align || 'left'">
                        <template slot-scope="scope">
                            <div v-if="item.operations">
                                <template v-for="operate in item.operations">
                                    <el-button 
                                        type="text"
                                        size="mini"
                                        :key="operate.label"
                                        @click="operate.click(scope.row)"
                                    >
                                    {{ operate.label }}
                                </el-button>
                                </template>
                            </div>
                            <template v-else>{{scope.row[item.value]}}</template>
                        </template>
                    </el-table-column>
                </template>
            </edu-table>
        </div>
        <!-- 流程类型 -->
        <edu-dialog
            :title="updateFlowTypeOpt.label"
            width="600px"
            :visible.sync="updateFlowTypeOpt.show"
            showCancelBtn
            :autoHeight=false
            confirmBtnText="确定"
            :close-on-click-modal="false"
            @close="closeFlowType"
            @confirm="updateFlowType">
            <el-form
                :model="updateFlowTypeOpt.data"
                ref="flowTypeForm"
                label-width="120px"
                :rules="updateFlowTypeRules">
                <el-row v-for="item in updateFlowTypeOpt.form" :key="item.label">
                    <el-form-item v-if="item.type === 'input'" :label="setColon(item.label)" :prop="item.name">
                        <el-input v-model="updateFlowTypeOpt.data[item.name]" :placeholder="item.placeholder"></el-input>
                    </el-form-item>
                    <el-form-item v-if="item.type === 'select'" :label="setColon(item.label)" :prop="item.name">
                        <el-select v-model="updateFlowTypeOpt.data[item.name]" style="width: 100%" clearable>
                            <el-option
                                v-for="it in selectOptType(item.optType)"
                                :key="it.value"
                                :label="it.label"
                                :value="it.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-row>
            </el-form>
        </edu-dialog>
        <!-- 设置 -->
        <edu-dialog
            :title="updateCertainTypeOpt.label"
            width="600px"
            :visible.sync="updateCertainTypeOpt.show"
            showCancelBtn
            :autoHeight=false
            confirmBtnText="确定"
            @close="closeCertainType"
            @confirm="updateCertainType"
            :close-on-click-modal="false">
            <el-form
                :model="updateCertainTypeOpt.data"
                ref="certainTypeForm"
                label-width="120px"
                :rules="updateCertainTypeRules">
                <el-row v-for="item in updateCertainTypeOpt.form" :key="item.label">
                    <el-form-item v-if="item.type === 'remote-select'" :label="setColon(item.label)" :prop="item.name">
                        <el-select
                            v-model="updateCertainTypeOpt.data[item.name]"
                            :remote-method="remoteAccessApprover"
                            :placeholder="item.placeholder"
                            filterable
                            remote
                            reserve-keyword
                            clearable
                            style="width:100%">
                            <el-option
                                v-for="it in item.options"
                                :key="it.code"
                                :label="it.name"
                                :value="it.code">
                                <span style="float: left">{{ it.name }}</span>
                                <span
                                    style="float: right; color: #8492a6; font-size: 13px"
                                >{{ it.code }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>


                    <el-form-item v-if="item.type === 'select'" :label="setColon(item.label)" :prop="item.name">
                        <el-select v-model="updateCertainTypeOpt.data[item.name]" 
                            style="width: 100%" clearable multiple filterable>
                            <el-option
                                v-for="it in item.options"
                                :key="it.value"
                                :label="it.label"
                                :value="it.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-row>
            </el-form>
        </edu-dialog>
    </div>
</template>

<script>
import * as API from 'common/src/api/sysMgt/flowTypeMgt.js'
export default {
    name: "flowTypeMgt",
    data() {
        return {
            // 流程类型列表页
            filterApprovalOpt: [
                {
                    name: "dynamic",
                    label: "动态审批",
                    optType: 1
                },
                {
                    name: "business",
                    label: "业务人员审批",
                    optType: 1
                },
                {
                    name: "special",
                    label: "特殊审批",
                    optType: 0
                }
            ],
            filterApproval: {
                dynamic: '',
                business: '',
                special: ''
            },
            queryFlowTypeParams: {
                name: '',
                pageNum: 1,
                pageSize: 20
            },
            flowTypeTableOpt: {
                data: [],
                column: [
                    { name: '类型名称', value: 'name', align: 'left' },
                    { name: 'CSE URL路径', value: 'url', align: 'left' },
                    { name: '动态审批', value: 'dynamic', switch: true, align: 'left' },
                    { name: '业务人员', value: 'business', switch: true, align: 'left' },
                    { name: '每级回调', value: 'callback', switch: true, align: 'left' },
                    { name: '审批类型编号', value: 'approvalNumber', align: 'left' },
                    { name: '特殊审批', value: 'specialApproval', switch: true, tag: true, align: 'left' },
                    { name: '操作', align: 'left', width: 150, operations: [
                        {
                            label: '编辑',
                            click: (row) => {
                                this.editFlowType(row)
                            }
                        },
                        {
                            label: '删除',
                            click: (row) => {
                                this.deleteFlowType(row)
                            }
                        },
                        {
                            label: '设置',
                            dynamicShow: true,
                            show: () => {
                                if (row.specialApproval) {
                                    return true
                                } else {
                                    return false
                                }
                            },
                            click: (row) => {
                                this.setFlowType(row)
                            }
                        }
                    ]},
                ],
                pageOpt: {
                    total: 0
                }
            },
            updateFlowTypeOpt: {
                label: '',
                // add or edit
                type: '',
                show: false,
                data: {
                    id: '',
                    name: '',
                    url: '',
                    dynamic: '',
                    business: '',
                    callback: '',
                    approvalNumber: '',
                    specialApproval: ''
                },
                form: [
                    {
                        name: 'name',
                        type: 'input',
                        label: '类型名称',
                        placeholder: ''

                    },
                    {
                        name: 'url',
                        type: 'input',
                        label: 'CSE URL路径',
                        placeholder: ''
                    },
                    {
                        name: 'dynamic',
                        type: 'select',
                        optType: 1,
                        label: '动态审批',
                        placeholder: ''
                    },
                    {
                        name: 'business',
                        type: 'select',
                        optType: 1,
                        label: '业务人员',
                        placeholder: ''
                    },
                    {
                        name: 'callback',
                        type: 'select',
                        optType: 1,
                        label: '每级回调',
                        placeholder: ''
                    },
                    {
                        name: 'approvalNumber',
                        type: 'input',
                        label: '审批类型编号',
                        placeholder: ''
                    },
                    {
                        name: 'specialApproval',
                        type: 'select',
                        optType: 0,
                        label: '特殊审批',
                        placeholder: ''
                    }
                ]
            },
            updateFlowTypeRules: {
                name: [
                    {
                        required: true, 
                        message: '请输入类型名称', 
                        trigger: 'blur'
                    }
                ],
                url: [
                    {
                        // type: 'url', 
                        // message: '请输入有效URL'
                    }
                ],
                dynamic: [
                    {
                        required: true, 
                        message: '请输入是否需要动态审批', 
                        trigger: 'blur'
                    }
                ],
                business: [
                    {
                        required: true, 
                        message: '请选择是否需要业务人员进行审批', 
                        trigger: 'blur'
                    }
                ],
                callback: [
                    {
                        required: true, 
                        message: '请选择是否需要每级回调', 
                        trigger: 'blur'
                    }
                ],
                approvalNumber: [
                    {
                        required: true, 
                        message: '请输入审批类型编号', 
                        trigger: 'blur'
                    },
                    {
                        // type: 'number', 
                        // message: '请输入有效数字编号'
                    }
                ],
                specialApproval: [
                    {
                        required: true, 
                        message: '请选择是否特殊审批', 
                        trigger: 'blur'
                    }
                ]
            },

            // 某流程类型 审批设置 
            queryCertainTypeParams: {
                typeId: '',
                approver: '',
                pageNum: 1,
                pageSize: 20
            },
            updateCertainTypeOpt: {
                label: '',
                show: false,
                data: {
                    id: '',
                    typeId: '',
                    approver: '',
                    depts: []
                },
                form: [
                    {
                        name: 'approver',
                        type: 'remote-select',
                        options: [],
                        label: '审批人',
                        placeholder: '请输入审批人'

                    },
                    {
                        name: 'depts',
                        type: 'select',
                        options: [],
                        label: '审批部门',
                        placeholder: ''
                    }
                ]
            },
            updateCertainTypeRules: {
                approver: [
                    {
                        required: true, 
                        message: '请选择审批人', 
                        trigger: 'blur'
                    }
                ],
                depts: [
                    {
                        required: true, 
                        message: '请选择审批部门', 
                        trigger: 'blur'
                    }
                ]
            },
            certainTypeTableOpt: {
                data: [],
                column: [
                    { name: '类型名称', value: 'name', align: 'left' },
                    { name: '审批人', value: 'approverName', align: 'left' },
                    { name: '审批部门', value: 'deptsNames', align: 'left' },
                    { name: '操作', align: 'left', width: 100, operations: [
                        {
                            label: '编辑',
                            click: (row) => {
                                this.editCertainType(row)
                            }
                        },
                        {
                            label: '删除',
                            click: (row) => {
                                this.deleteCertainType(row)
                            }
                        }
                    ]},
                ],
                pageOpt: {
                    total: 0
                }
            },
            // common config
            label: {
                flowTypeList: '流程类型列表',
                typeName: '类型名称',
                add: '新增',
                edit: '编辑',
                goBack: '返回',
                approver: '审批人'
            },
            needOrNot: [
                {
                    label: '需要',
                    value: 1
                },
                {
                    label: '不需要',
                    value: 2
                }
            ],
            yesOrNo: [
                {
                    label: '是',
                    value: 1
                },
                {
                    label: '否',
                    value: 2
                }
            ],
            needMap: {
                1: '需要',
                2: '不需要'
            },
            yesMap: {
                1: '是',
                2: '否'
            },
            currentPage: 'home',
            breadPath: {
                label:'流程类型列表',
                key: 'home',
                children:[
                    {
                        key: 'set',
                        label: '设置'
                    }
                ]
            }
        };
    },
    watch: {
      currentPage (val) {
        if (val === 1) {
            document.getElementsByClassName('el-main')[0].scrollTop = 0;
            this.searchParam.pageNum_ = 1;
            this.searchMyInformations();
        }
      },
      'updateCertainTypeOpt.data.depts'(val) {
          console.log(val)
      }
    },
    created() {
        // 查询流程类型列表
        this.fetchFlowTypeList()
        // 查询审批部门
        this.getApprovalDepts()
    },
    methods: {
        // 流程类型 api
        async fetchFlowTypeListFn(params) {
            try {
                let resp = await API.queryWfTypeList(params);
                this.flowTypeTableOpt.pageOpt.total = resp.data.total_
                this.flowTypeTableOpt.data = resp.data.list.map(item => {
                    let {
                        id,
                        typeName: name,
                        cseURL: url,
                        needTutor: dynamic,
                        needBusiness: business,
                        needCallback: callback,
                        serialNum: approvalNumber,
                        needSpecial: specialApproval
                    } = item
                    return {
                        id,
                        name,
                        url,
                        dynamic,
                        business,
                        callback,
                        approvalNumber,
                        specialApproval
                    }
                })
            } catch (error) {
                console.log(error)
            }
        },
        async updateFlowTypeFn(params) {
            try {
                let resp;
                if (this.updateFlowTypeOpt.type === 'add') {
                    resp = await API.addWfType(params)
                } else {
                    resp = await API.updateWfType(params)
                }
                if (resp) {
                    this.closeFlowType()
                    this.fetchFlowTypeList()
                }
            } catch (error) {
                console.log(error)
            }
        },
        async deleteFlowTypeFn(params) {
            try {
                let resp = await API.deleteWfTypeById(params);
                if (resp) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                    this.fetchFlowTypeList()
                }
            } catch (error) {
                console.log(error)
            }
        },

        // 某类型流程审批配置 api
        async fetchCertainTypeListFn(params) {
            try {
                let resp = await API.queryWfTypeApproverList(params);
                this.certainTypeTableOpt.pageOpt.total = resp.data.total_
                this.certainTypeTableOpt.data = resp.data.list.map(item => {
                    let {
                        id,
                        typeName: name,
                        typeId,
                        approverName,
                        approverId: approver,
                        approverFaculty: depts,
                    } = item
                    let facultyNames = []
                    depts.split(',').forEach(item => {
                        this.updateCertainTypeOpt.form[1].options.forEach((it) => {
                            if (it.value === item) {
                                facultyNames.push(it.label)
                            } 
                        })
                    })
                    return {
                        id,
                        name,
                        typeId,
                        approver,
                        approverName,
                        depts: depts.split(','),
                        deptsNames: facultyNames.join('、')
                    }
                })
            } catch (error) {
                console.log(error)
            }
        },
        async updateCertainTypeFn(params) {
            try {
                let resp;
                if (this.updateCertainTypeOpt.type === 'add') {
                    resp = await API.addWfTypeApprover(params)
                } else {
                    resp = await API.updateWfTypeApprover(params)
                }
                if (resp) {
                    this.closeCertainType()
                    this.fetchCertainTypeList()
                }
            } catch (error) {
                console.log(error)
            }
        },
        async deleteCertainTypeFn(params) {
            try {
                let resp = await API.deleteWfTypeApproverById(params);
                if (resp) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                    this.fetchCertainTypeList()
                }
            } catch (error) {
                console.log(error)
            }
        },
        async getApprover(query) {
            let params = {
                condition: query,
                // faculty: '',
                pageSize_: 100,
                pageNum_: 0
            }
            try {
                let resp = await API.findTeacherInfoListInGroupId(params);
                if (resp && resp.data) {
                    this.updateCertainTypeOpt.form[0].options = resp.data.list.map(item => {
                        return _.pick(item, ['name', 'code'])
                    });
                }
            } catch (error) {
                console.log(error)
            }
        },
        async getApprovalDepts() {
            try {
                let resp = await API.findDept(1);
                if (resp && resp.data) {
                    this.updateCertainTypeOpt.form[1].options = resp.data.map(item => {
                        let {
                            deptName: label,
                            deptCode: value
                        } =  _.pick(item, ['deptName', 'deptCode'])
                        return {
                            label,
                            value
                        }
                    })
                }
            } catch (error) {
                console.log(error)
            }
        },

        // common 
        reset(formName) {
            this.$refs[formName].resetFields();
        },
        setColon(label) {
            return `${label}: `;
        },
        goBack() {
            this.queryCertainTypeParams = {
                approver: '',
                typeId: '',
                pageSize: 20,
                pageNum: 1
            }
            this.currentPage = 'home';
        },
        selectOptType(type) {
            if (type === 1) {
                return this.needOrNot;
            } else if (type === 0) {
                return this.yesOrNo;
            }
        },

        // 流程类型
        fetchFlowTypeList() {
            let {
                name: typeName,     
                dynamic: needTutor,    
                business: needBusiness, 
                special: needSpecial,
                pageNum: pageNum_,
                pageSize: pageSize_
            } = Object.assign({}, this.filterApproval, this.queryFlowTypeParams)
            this.fetchFlowTypeListFn({
                typeName,     
                needTutor,    
                needBusiness, 
                needSpecial,
                pageNum_,
                pageSize_
            })
        },
        queryFlowType() {
            this.queryFlowTypeParams.name = ''
            this.fetchFlowTypeList()
        },
        addFlowType() {
            this.updateFlowTypeOpt.label = '新增'
            this.updateFlowTypeOpt.type = 'add'
            this.updateFlowTypeOpt.show = true
        },
        editFlowType(row) {
            this.updateFlowTypeOpt.label = '编辑'
            this.updateFlowTypeOpt.type = 'edit'
            this.updateFlowTypeOpt.show = true
            this.$nextTick(() => {
                this.updateFlowTypeOpt.data = JSON.parse(JSON.stringify(row))
            })
        },
        deleteFlowType(row) {
            this.$confirm(`确认删除${row.name}流程类型吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let id = row.id
                this.deleteFlowTypeFn(id)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        setFlowType(row) {
            this.currentPage = 'set';
            this.queryCertainTypeParams.typeId = row.id
            this.fetchCertainTypeList()
        },
        updateFlowType() {
            this.$refs.flowTypeForm.validate(valid => {
                if (valid) {
                    let {
                        id: id,
                        name: typeName,
                        url: cseURL,
                        dynamic: needTutor,
                        business: needBusiness,
                        callback: needCallback,
                        approvalNumber: serialNum,
                        specialApproval: needSpecial
                    } = this.updateFlowTypeOpt.data
                    let params = this.updateFlowTypeOpt.type === 'add'
                        ? { 
                            typeName,
                            cseURL,
                            needTutor,
                            needBusiness,
                            needCallback,
                            serialNum,
                            needSpecial 
                        }
                        : {
                            id,
                            typeName,
                            cseURL,
                            needTutor,
                            needBusiness,
                            needCallback,
                            serialNum,
                            needSpecial 
                        }
                    this.updateFlowTypeFn(params)
                }
            })
        },
        closeFlowType() {
            this.$nextTick(() => {
                this.reset('flowTypeForm')
            })
            this.updateFlowTypeOpt.show = false
        },
        flowTypePageChange({ pageNum, pageSize }) {
            this.queryFlowTypeParams.pageNum = pageNum
            this.queryFlowTypeParams.pageSize = pageSize
            this.fetchFlowTypeList()
        },


        // 类型审批设置
        fetchCertainTypeList() {
            let {
                typeId: typeId,
                approver: approverId,     
                pageNum: pageNum_,
                pageSize: pageSize_
            } = this.queryCertainTypeParams
            this.fetchCertainTypeListFn({
                typeId,
                approverId,
                pageNum_,
                pageSize_
            })
        },
        addCeratainType() {
            this.updateCertainTypeOpt.label = '新增'
            this.updateCertainTypeOpt.type = 'add'
            this.updateCertainTypeOpt.show = true
        },
        editCertainType(row) {
            this.updateCertainTypeOpt.label = '编辑'
            this.updateCertainTypeOpt.type = 'edit'
            this.$nextTick(() => {
                this.updateCertainTypeOpt.data = JSON.parse(JSON.stringify(row))
                this.updateCertainTypeOpt.form[0].options = [
                    {
                        name: row.approverName,
                        code: row.approver
                    }
                ]
            })
            this.updateCertainTypeOpt.show = true
        },
        deleteCertainType(row) {
            this.$confirm(`确认删除该审批配置吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let id = row.id
                this.deleteCertainTypeFn(id)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        updateCertainType() {
            this.$refs.certainTypeForm.validate(valid => {
                if (valid) {
                    let {
                        id,
                        approver: approverId,
                        depts: approverFaculty
                    } = this.updateCertainTypeOpt.data
                    let { typeId } = this.queryCertainTypeParams
                    let params = this.updateCertainTypeOpt.type === 'add'
                        ? { 
                            typeId,
                            approverId,
                            approverFaculty: approverFaculty.join(',')
                        }
                        : {
                            id,
                            approverId,
                            approverFaculty: approverFaculty.join(',')
                        }
                    this.updateCertainTypeFn(params)
                }
            })
        },
        remoteAccessApprover(query) {
            if (!!query) {
                setTimeout(() => {
                    this.getApprover(query)
                }, 200);
            } else {
                this.updateCertainTypeOpt.form[0].options = [];
            }
        },
        closeCertainType() {
            this.$nextTick(() => {
                this.reset('certainTypeForm')
            })
            this.updateCertainTypeOpt.show = false
        },
        certainTypePageChange({ pageNum, pageSize }) {
            this.queryCertainTypeParams.pageNum = pageNum
            this.queryCertainTypeParams.pageSize = pageSize
            this.fetchCertainTypeList()
        }
    }
};
</script>

<style lang="scss" scoped>
.searchArea {
    margin-bottom: 16px;
    .el-button+.el-button {
        margin-right: 8px;
    }
}
</style>
